package cc.linker.steplink.crm.controller.robot;


import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.IClientRobotService;
import cc.linker.steplink.crm.service.IMarketRobotService;
import cc.linker.steplink.crm.service.ISysConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 智能营销机器人
 */
@Slf4j
@RestController
@RequestMapping("/marketrobot")
public class MarketRobotController {

    @Autowired
    private ISysConfig sysConfigService;

    @Autowired
    private IClientRobotService iClientRobotService;

    @Autowired
    private IMarketRobotService marketRobotService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private CustomerService customerService;

    @Value("${system.scrm.sync.contentUrl}")
    private String synccontentUrl;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.defimg}")
    private String defimg;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoUtil userInfoUtil;

//    @GetMapping("/test")
//    public void test(){
//        stringRedisTemplate.opsForValue().increment("aaaa", 1);
//        System.out.println(stringRedisTemplate.opsForValue().get("aaaa"));
//    }


    /**
     * 获取智能营销机器人配置
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getconf")
    public Map GetConf(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, Object> resMap = new HashMap<>();
        String marketRobotLimit = sysConfigService.getSysConfByName(orgId, "marketRobotLimit");
        if (null == marketRobotLimit) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "1");
            tmpParam.put("desc", "智能营销机器人群发推送上限");
            tmpParam.put("name", "marketRobotLimit");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("marketRobotLimit", "1");
        } else {
            resMap.put("marketRobotLimit", marketRobotLimit);
        }

        String marketRobotStartTime = sysConfigService.getSysConfByName(orgId, "marketRobotStartTime");
        if (null == marketRobotStartTime) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "08:00:00");
            tmpParam.put("desc", "智能营销机器人营销时间");
            tmpParam.put("name", "marketRobotStartTime");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("marketRobotStartTime", "08:00:00");
        } else {
            resMap.put("marketRobotStartTime", marketRobotStartTime);
        }
        return resMap;
    }

    /**
     * 设置智能营销机器人配置
     *
     * @param session
     * @param map
     * @return
     * @throws GlobalException
     */
    @PostMapping("/setconf")
    public Map setConf(HttpServletRequest request, @RequestBody Map<String, String> map) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
            String orgId = userinfo.getOrgId();
            if (StringUtils.isEmpty(orgId)) {
                throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
            }

            Map<String, String> resData = new HashMap<>();
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            String marketRobotLimit = sysConfigService.getSysConfByName(orgId, "marketRobotLimit");
            resData.put("marketRobotLimit", marketRobotLimit);
            if (null != map.get("marketRobotLimit")) {
                if (null != marketRobotLimit) {
                    tmpParam.put("value", map.get("marketRobotLimit"));
                    tmpParam.put("name", "marketRobotLimit");
                    Boolean setLimit = sysConfigService.updateSysConf(tmpParam);
                    if (!setLimit) {
                        throw GlobalException.build("操作失败");
                    }
                } else {
                    throw GlobalException.build("非法操作");
                }
                resData.put("marketRobotLimit", map.get("marketRobotLimit"));
            }

            String marketRobotStartTime = sysConfigService.getSysConfByName(orgId, "marketRobotStartTime");
            resData.put("marketRobotStartTime", marketRobotStartTime);
            if (null != map.get("marketRobotStartTime")) {
                if (null != marketRobotLimit) {
                    tmpParam.put("value", map.get("marketRobotStartTime"));
                    tmpParam.put("name", "marketRobotStartTime");
                    Boolean setTime = sysConfigService.updateSysConf(tmpParam);
                    if (!setTime) {
                        throw GlobalException.build("操作失败");
                    }
                } else {
                    throw GlobalException.build("非法操作");
                }
                resData.put("marketRobotStartTime", map.get("marketRobotStartTime"));
            }
            return resData;
    }

    /**
     * 获取智能营销机器人开关
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getswitch")
    public Map getSwitch(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, Object> resMap = new HashMap<>();
        String marketRobotSwitch = sysConfigService.getSysConfByName(orgId, "marketRobotSwitch");
        if (null == marketRobotSwitch) {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("value", "0");
            tmpParam.put("desc", "智能营销机器人开关(0:关闭，1:打开)");
            tmpParam.put("name", "marketRobotSwitch");
            sysConfigService.addSysConf(tmpParam);
            resMap.put("marketRobotSwitch", "0");
        } else {
            resMap.put("marketRobotSwitch", marketRobotSwitch);
        }
        Map<String, Object> orgFunction = customerService.getOrgFunctionOrgId(orgId);
        Integer robotNum = 0;
        if (orgFunction == null || StringUtils.isEmpty(orgFunction.get("marNum"))) {
            robotNum = 0;
        } else if (!StringUtils.isEmpty(orgFunction.get("marExpireDate"))) {
            // 判断时间是否到期
            Long expireTime = dateToStamp(orgFunction.get("marExpireDate").toString() + " 00:00:00");
            Long nowTime = System.currentTimeMillis();
            if (nowTime > expireTime) {
                robotNum = 0;
            } else {
                robotNum = Integer.parseInt(orgFunction.get("marNum").toString());
            }
        }
        // 获取当前机构机器人数量
        resMap.put("robotNum", robotNum);

        return resMap;
    }

    /**
     * 设置智能营销机器人开关
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @PostMapping("/changeswitch")
    public Map changeSwitch(HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);

        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Map<String, String> resData = new HashMap<>();
        Boolean setLimit = false;
        String marketRobotSwitch = sysConfigService.getSysConfByName(orgId, "marketRobotSwitch");
        if (null == marketRobotSwitch) {
            throw GlobalException.build("非法操作");
        } else {
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orgId", orgId);
            tmpParam.put("name", "marketRobotSwitch");
            if ("0".equals(marketRobotSwitch)) {
                tmpParam.put("value", "1");
                resData.put("marketRobotSwitch", "1");
                tmpParam.put("dynamicContent", "智能营销机器人开启");
                tmpParam.put("dynamicType", "3");
                dynamicService.recording(request, 9,"开启智能营销机器人");
            } else {
                tmpParam.put("value", "0");
                resData.put("marketRobotSwitch", "0");
                tmpParam.put("dynamicContent", "智能营销机器人关闭");
                tmpParam.put("dynamicType", "4");
                dynamicService.recording(request, 10,"关闭智能营销机器人");
            }
            setLimit = sysConfigService.updateSysConf(tmpParam);
            tmpParam.put("robotType", "market");
            sysConfigService.saveRobotDynamic(tmpParam);
        }
        if (setLimit) {
            return resData;
        }
        throw GlobalException.build("操作失败");
    }


    /**
     * 添加营销组合任务
     *
     * @param session
     * @param map
     * @return
     * @throws GlobalException
     */
    @PostMapping("/addcomposelist")
    public Boolean addCompose(HttpServletRequest request, @RequestBody Map<String, String> map) throws GlobalException, IOException, URISyntaxException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if (null == map.get("composeName") || "".equals(map.get("composeName"))) {
            throw GlobalException.build("营销组合名称不能为空。");
        }
        if (null == map.get("labelId") || "".equals(map.get("labelId"))) {
            throw GlobalException.build("类别不能为空。");
        }
        if (null == map.get("articleIds") || "".equals(map.get("articleIds"))) {
            throw GlobalException.build("请添加文章。");
        }

        List<String> artIds = new ArrayList<>();
        String[] articleIds = map.get("articleIds").split(",");
        for (String str : articleIds) {
            String[] artidplits = str.split(",");
            artIds.addAll(Arrays.asList(artidplits));
        }

        int composeNum = marketRobotService.countComposeByName(map.get("composeName"), orgId);
        if (composeNum > 0) {
            throw GlobalException.build("已存在名称为[" + map.get("composeName") + "]的任务");
        }

        int artcount = marketRobotService.countArticleByArticleIds(artIds, orgId);
        if (artcount > 0) {
            throw GlobalException.build("选择的文章已被添加过");
        }

        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_LIST_BY_IDS;
        Map<String, Object> param = new HashMap<>();
        param.put("ids", map.get("articleIds"));
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        List<Map<String, Object>> resList = new ArrayList<>();
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                resList = (ArrayList) res.get("data");
                String composeId = UUID.randomUUID().toString();
                for (Map<String, Object> va : resList) {
                    String artImg = defimg;
                    if (null != va.get("newsCover")) {
                        List coverList = (List) va.get("newsCover");
                        if (coverList.size() > 0) {
                            artImg = coverList.get(0).toString();
                        }
                    }

                    Map<String, String> data = new HashMap<>();
                    data.put("taskId", UUID.randomUUID().toString());
                    data.put("articleId", va.get("id").toString());
                    data.put("articleTitle", va.get("newsName") == null ? "标题" : va.get("newsName").toString());
                    data.put("articleDesc", va.get("newsSummary") == null ? "简介" : va.get("newsSummary").toString());
                    data.put("articleUrl", va.get("url") == null ? "" : va.get("url").toString());
                    data.put("url", va.get("url") == null ? "" : va.get("url").toString());
                    data.put("articleImage", artImg);
                    //文章类型
                    data.put("articleType", StringUtils.isEmpty(va.get("isGoods")) ? "0" : va.get("isGoods").toString());
                    data.put("labelId", map.get("labelId"));
                    data.put("composeName", map.get("composeName"));
                    data.put("taskType", "market");
                    data.put("composeId", composeId);
                    data.put("orgId", orgId);
                    data.put("readTime", va.get("readTime") == null ? "0" : (String) va.get("readTime"));
                    data.put("articleLabel", StringUtils.isEmpty(va.get("newsLabel")) ? "" : va.get("newsLabel").toString());
                    Boolean addRes = marketRobotService.addMarketRobotList(data);
                    if (!addRes) {
                        LOGGER.warn("提交了重复的文章ID");
                    }
                }
                return true;
            } else {
                throw GlobalException.build("请求失败");
            }
        } else {
            throw GlobalException.build("请求失败");
        }

    }


    /**
     * 删除营销组合
     *
     * @param session
     * @param map
     * @return
     * @throws GlobalException
     */
    @PostMapping("/delcompose")
    public Boolean delConpose(HttpServletRequest request, @RequestBody Map<String, String> map) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
            String orgId = userinfo.getOrgId();
            if (StringUtils.isEmpty(orgId)) {
                throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
            }
            if (StringUtils.isEmpty(map.get("composeId"))) {
                throw GlobalException.build("参数错误");
            }
            map.put("orgId", orgId);
            return marketRobotService.delConpose(map);
    }

    /**
     * 获取组合详情
     *
     * @param session
     * @return
     * @throws GlobalException
     * @throws IOException
     * @throws URISyntaxException
     */
    @GetMapping("/getcomposeinfo")
    public Map getComposeInfo(HttpServletRequest request, @RequestParam(value = "composeId", defaultValue = "", required = true) String composeId) throws GlobalException, IOException, URISyntaxException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);

            String orgId = userinfo.getOrgId();
            if (StringUtils.isEmpty(orgId)) {
                throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
            }
            if (StringUtils.isEmpty(composeId)) {
                throw GlobalException.build("参数错误");
            }
            Map<String, Object> resMap = new HashMap<>();
            List<Map<String, String>> artIdList = marketRobotService.getComposeInfo(composeId);
            if (artIdList.size() > 0) {
                resMap.put("composeName", artIdList.get(0).get("composeName"));
                resMap.put("labelIds", artIdList.get(0).get("labelIds"));
                resMap.put("newsList", artIdList);
                return resMap;
            } else {
                throw GlobalException.build("参数错误");
            }
    }


    /**
     * 获取营销组合列表
     *
     * @param session
     * @param composeName
     * @param labelId
     * @param composeStatus
     * @param pageIndex
     * @param pageSize
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getcomposelist")
    public Object getComposeList(HttpServletRequest request,
                                 @RequestParam(value = "composeName", defaultValue = "", required = false) String composeName,
                                 @RequestParam(value = "labelId", defaultValue = "", required = false) String labelId,
                                 @RequestParam(value = "composeStatus", defaultValue = "", required = false) String composeStatus,
                                 @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                 @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) throws GlobalException {

        PageHelper.startPage(pageIndex, pageSize);
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);

            String orgId = userinfo.getOrgId();
            if (StringUtils.isEmpty(orgId)) {
                throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
            }
            Map<String, Object> param = new HashMap<>();
            param.put("orgId", orgId);
            param.put("taskType", "market");
            if (!StringUtils.isEmpty(composeName)) {
                param.put("composeName", composeName);
            }
            if (!StringUtils.isEmpty(labelId)) {
                String[] paramsplit = labelId.split(",");
                List<String> paramlabelId = new ArrayList<>(Arrays.asList(paramsplit));
                param.put("labelIds", paramlabelId);
            }
            if (!StringUtils.isEmpty(composeStatus)) {
                param.put("composeStatus", composeStatus);
            }
            List<Map<String, String>> marketRobotList = marketRobotService.getMarketRobotList(param);
            for (Map<String, String> data : marketRobotList) {
                List<String> artLabel = new ArrayList<>();
                String[] labelIds = data.get("labelIds").split(",");
                for (String str : labelIds) {
                    String[] artsplits = str.split(",");
                    artLabel.addAll(Arrays.asList(artsplits));
                }
                List<String> labelNames = marketRobotService.getLabelNameByIds(artLabel);
                String labelName = StringUtils.collectionToDelimitedString(labelNames, ",");
                data.put("labelName", labelName);
                data.remove("labelIds");
            }
            return new PageInfo<>(marketRobotList);
    }

    /**
     * 修改任务状态
     *
     * @param session
     * @param param
     * @return
     * @throws GlobalException
     */
    @PostMapping("/changecompose")
    public Boolean changeCompose(HttpServletRequest request, @RequestBody Map<String, String> param) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (null == param.get("composeId")) {
            throw GlobalException.build("参数错误");
        }
        Map<String, String> data = new HashMap<>();
        data.put("composeId", param.get("composeId"));
        String composeStatus = marketRobotService.getComposeStatus(param.get("composeId"));
        if ("1".equals(composeStatus)) {
            data.put("composeStatus", "0");
        } else {
            data.put("composeStatus", "1");
        }
        return marketRobotService.setComposeStatus(data);
    }

    /**
     * 用户活跃度统计
     *
     * @param session
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getactivechart")
    public List getActiveChart(HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        List<Map<String, Object>> activeChartList = marketRobotService.getActiveChart(orgId);
        return activeChartList;

    }

    /**
     * @Description: 获取机器人动态
     * @Param: [session]
     * @Return: java.util.List<cc.linker.steplink.crm.domain.RobotDynamicPo> 动态列表
     * @Author: 锋
     * @Date: 2019/9/3 16:17
     * @Version: 1.8.3
     */
    @GetMapping("/getRobotDynamicList")
    public Object getRobotDynamicList(HttpServletRequest request,
                                      @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        PageHelper.startPage(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("robotType", "market");
        return new PageInfo<>(marketRobotService.getRobotDynamicList(param));
    }

    /**
     * 获取智能营销机器人粉丝数据
     *
     * @return
     * @throws Exception
     */
    @GetMapping("getfansdata")
    public Map<String, Object> getFansData(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> result = new HashMap<>();
        Integer totalFans = iClientRobotService.getMaintainNum(orgId);
        Integer activeFans = iClientRobotService.getActiveFans(orgId);
        String activeRate = iClientRobotService.getActivity(orgId);
        Integer maintainTimes = iClientRobotService.getMaintainTimes(orgId, "market");
        Integer maintainPerson = iClientRobotService.getMaintainPerson(orgId, "market");
        Integer orderCount = iClientRobotService.getOrderCount(orgId);

        result.put("totalFans", totalFans);
        result.put("activeFans", activeFans);
        result.put("activeRate", activeRate);
        result.put("maintainTimes", maintainTimes);
        result.put("maintainPerson", maintainPerson);
        result.put("orderCount", orderCount);
        return result;
    }

    /**
     * 营销数据块
     *
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("marketblock")
    public Map<String, Object> maintainBlock(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        String tallyTime = new SimpleDateFormat("yyyy-MM-dd").format((System.currentTimeMillis()) - 86400000L);
        param.put("orgId", orgId);
        param.put("tallyTime", tallyTime);
        param.put("type", "market");
        Map<String, Object> res = iClientRobotService.maintainBlock(param);
        if (null == res || res.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("tallyTime", tallyTime);
            result.put("maintainNum", 0);
            result.put("tranRate", "0.00");
            result.put("readTime", 0);
            result.put("followNum", 0);
            result.put("unfollowNum", 0);
            result.put("activity", "0.00");
            return result;
        }
        return res;
    }

    /**
     * 营销数据折线图
     *
     * @param session
     * @param type
     * @return
     * @throws Exception
     */
    @GetMapping("marketchart")
    public List<Map<String, Object>> marketChart(HttpServletRequest request, String type) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        param.put("orgId", orgId);
        param.put("type", "market");
        param.put("kind", type);
        List<Map<String, Object>> res = iClientRobotService.robotChart(param);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 30; i > 0; i--) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.DAY_OF_MONTH, -i);
            String endDate = sdf.format(now.getTime());
            Integer up = 0;
            for (Map<String, Object> attribute : res) {
                if (attribute.get("tallyTime").toString().equals(endDate)) {
                    list.add(attribute);
                    up = 1;
                }
            }
            if (up == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("tallyTime", endDate);
                switch (type) {
                    case "maintainNum":
                        map.put("maintainNum", 0);
                        break;
                    case "tranRate":
                        map.put("tranRate", "0.00");
                        break;
                    case "readTime":
                        map.put("readTime", 0);
                        break;
                    case "follow":
                        map.put("followNum", 0);
                        map.put("unfollowNum", 0);
                        break;
                    case "activity":
                        map.put("activity", "0.00");
                        break;
                    default:
                        break;
                }
                list.add(map);
            }
        }
        return list;
    }


    @Value("${system.scrm.sync.contentUrl}")
    private String articleurl;

    /**
     * @Description: 获取营销文库可选文章列表
     * @Param: 分页参数，分类，标签
     * @Return: 文章列表
     * @Author: 锋
     * @Date: 2019/9/6 17:20
     * @Version: 1.8.3
     */
    /**
     * @Modify: wuyue
     * @Date: 2019/9/9 9:30
     * @Description: 加参数:区分 普通文章 还是商品文章
     * @Version: v1.8.3
     */
    @GetMapping("/getLibraryArticleList")
    public Object getLibraryArticleList(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        int pn = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pn")) ? "1" : request.getParameter("pn"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));
        String classId = request.getParameter("classId");
        String labels = request.getParameter("labels");
        String sendState = request.getParameter("sendState");
        String filter = request.getParameter("filter");
        String sendType = request.getParameter("sendType");
        // 是否过滤已推送过的文章，默认过滤
        if (StringUtils.isEmpty(filter)) {
            filter = "1";
        }
        Integer integerSendState;
        if (sendState == null) {
            integerSendState = -1;
        } else {
            integerSendState = Integer.valueOf(sendState);
        }
        String orgId = userinfo.getOrgId();
        /**
         * @Modify: wuyue
         * @Date: 2019/9/20 15:17
         * @Description: 褚克勤(842381722) 15:12:22修改下，调用内容库的时候不要传用户,这个接口需要返回机构下的所有文章
         * @Version: v1.9.1
         */
//        String adminId = userinfo.getAdminId();
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("organizationNum", orgId);
//        reqMap.put("userId", adminId);
        reqMap.put("pageIndex", pn);
        reqMap.put("perPage", pageSize);
        reqMap.put("sendState", integerSendState);
        if(!StringUtils.isEmpty(classId)){
            reqMap.put("classificationId", classId);
        }
        if(!StringUtils.isEmpty(labels)){
            reqMap.put("labelName", labels);
        }
        if (!StringUtils.isEmpty(sendType)) {
            reqMap.put("sendType", sendType);
        }
        if ("1".equals(filter)) {
            List<String> localArticleIds = marketRobotService.getLocalArticleIds(orgId);
            String ids = org.apache.commons.lang.StringUtils.join(localArticleIds, ",");
            reqMap.put("id", ids);
        }

        String isGoods = request.getParameter("isGoods");
        if (!StringUtils.isEmpty(isGoods)) {
            reqMap.put("isGoods", Integer.valueOf(isGoods));
        }

        String url = systemProperties.getSync().getContentUrl() + ContentConstant.NEWS_BY_STEP;
        String res = httpService.doGet(url, reqMap, ContentConstant.HEADER);
        Map data = (Map) JSON.parse(res);
        if(null == data){
            throw GlobalException.build("请求内容库失败");
        }
        if (!"200".equals(data.get("code"))) {
            throw GlobalException.build(data.get("message").toString());
        }
        Map<String, Object> rsMap = new HashMap<>();
        rsMap.put("count", data.get("count"));
        rsMap.put("pn", data.get("pageIndex"));
        rsMap.put("pageSize", data.get("perPage"));
        rsMap.put("totalPage", data.get("totalPage"));
        rsMap.put("list", data.get("data"));
        return rsMap;
    }

    /*
     * 将时间转换为时间戳
     */
    public static Long dateToStamp(String s) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        return date.getTime();
    }
}
